﻿using System.Collections.Generic;
using UnityEngine;

namespace Core
{
    [Buff]
    public class IntervalBuff : BuffSystem
    {
        private float intervalTime;
        private float interval;
        private float range;
        private int buffId;
        private bool isRange;
        private List<Unit> units;
        protected override void OnAwake()
        {
            float.TryParse(config.param1, out interval);
            float.TryParse(config.param2, out range);
            int.TryParse(config.param3, out buffId);
            intervalTime = interval;
            isRange = range > 0;

            if(isRange)
            {
                units = new List<Unit>();
#if UNITY_EDITOR
                var drawRange = target.transform.gameObject.AddComponent<DrawRange>();
                drawRange.radius = range;
                drawRange.color = Color.green;
#endif
            }
        }

        protected override void OnFixedUpdate()
        {
            intervalTime -= Time.fixedDeltaTime;
            if (intervalTime > 0)
                return;

            // 搜索圆形范围内所有单位增加buff
            if(isRange)
            {
                Utils.GetUnitByRangeXZ(target, range, units);
                if(units.Count > 0)
                {
                    foreach (var unit in units)
                    {
                        unit.GetComponent<BuffComponent>().AddBuff(buffId);
                    }
                }
            }
            else
            {
                // 仅自己上buff
                target.GetComponent<BuffComponent>().AddBuff(buffId);
            }

            intervalTime = interval;
        }
    }
}